package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.log.LogObjectHolder;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.db4.service.TeamService;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyWmtxlParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TakeAwayTxlParam;
import cn.stylefeng.guns.sys.modular.system.model.result.TakeAwayResult;
import cn.stylefeng.guns.sys.modular.system.model.result.YyjlResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyTxlService;
import cn.stylefeng.guns.sys.modular.system.service.BtyWmtxlService;
import cn.stylefeng.guns.sys.modular.system.service.GcgWsjdService;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 通讯录管理控制器
 *
 * @author 张凯
 * @date 2020/8/5
 */
@Controller
@RequestMapping("/btyTxl")
public class BtyTxlController extends BaseController {

    private static final String PREFIX = "/modular/system/btyTxl/";
    //返回值
    protected static SuccessResponseData SUCCESS_TIP = new SuccessResponseData();
    //定义全局变量用来传餐厅的ID
    Long ct_id;

    @Autowired
    private BtyTxlService btyTxlService;
    @Resource
    private TeamService teamService;
    @Resource
    private GcgWsjdService wsjdService;
    @Resource
    private BtyWmtxlService btyWmtxlService;


    /**
     * 跳转到通讯录列表首页/btyTxl/btyTxlWm_update
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "btyTxl.html";
    }

    /**
     * 跳转到外卖通讯录列表首页
     */
    @RequestMapping("/waimai")
    public String takeAwayIndex() {
        return PREFIX + "btyTxlWaiMai.html";
    }

    /**
     * 跳转到外卖通讯录新列表首页
     */
    @RequestMapping("/waimaiTxl")
    public String waimaiTxl() {
        return PREFIX + "btyWaimai.html";
    }

    /**
     * 跳转到外卖通讯录新列表添加
     */
    @RequestMapping("/waimaiAdd")
    public String waimaiAdd(BtyWmtxl btyWmtxl) {
        return PREFIX + "btyWaimai_add.html";
    }

    /**
     * 添加外卖通讯录
     */
    @RequestMapping("/waimaiAddList")
    @ResponseBody
    public ResponseData waimaiAddList(BtyWmtxl btyWmtxl) {
        return btyTxlService.waimaiAddList(btyWmtxl);
    }

    /**
     * 外卖通讯录详情
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyWmtxl btyWmtxl) {
        BtyWmtxl detail = this.btyWmtxlService.getById(btyWmtxl.getId());
        return ResponseData.success(detail);
    }

    /**
     * 删除外卖通讯录
     * @param param
     * @return
     */
    @RequestMapping(value = "/deleteWm")
    @ResponseBody
    public Object deleteWm(BtyWmtxlParam param) {
        this.btyWmtxlService.delete(param);
        return SUCCESS_TIP;
    }

    /**
     * 外卖通讯录列表
     * @return
     */
    @RequestMapping(value = "/takeAwayList")
    @ResponseBody
    public LayuiPageInfo takeAwayTxlList(TakeAwayTxlParam takeAwayTxlParam){
        return btyTxlService.takeAwayTxlList(takeAwayTxlParam);
    }

    /**
     * 外卖通讯录导出列表
     * @return
     */
    @RequestMapping(value = "/takeAwayExportList")
    @ResponseBody
    public List<TakeAwayResult> takeAwayExportList(TakeAwayTxlParam takeAwayTxlParam){
        return btyTxlService.takeAwayExportList(takeAwayTxlParam);
    }


    /**
     * 外卖通讯录新列表
     * @return
     */
    @RequestMapping(value = "/wmList")
    @ResponseBody
    public LayuiPageInfo wmList(TakeAwayTxlParam takeAwayTxlParam){
        return btyTxlService.wmList(takeAwayTxlParam);
    }

    /**
     * 外卖通讯录新导出列表
     * @return
     */
    @RequestMapping(value = "/wmExportList")
    @ResponseBody
    public List<TakeAwayResult> wmExportList(TakeAwayTxlParam takeAwayTxlParam){
        return btyTxlService.wmExportList(takeAwayTxlParam);
    }


    /**tSearchExport
     * 外卖通讯录获取营运经理列表
     * @return
     */
    @RequestMapping(value = "/yyjlList")
    @ResponseBody
    public List<YyjlResult> getyyjlList(){
        return btyTxlService.getyyjlList();
    }

    /**
     * 外卖通讯录获取天财店名列表
     * @return
     */
    @RequestMapping(value = "/tcList")
    @ResponseBody
    public List<Map> tcList(){
        return btyTxlService.tcList();
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String ctbh, String dm, String csqy, String yyjl, String dd, String timeLimit, Integer status) {

        String tel = "";
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1] + " 23:59:59";
        }
        //获取用户的帐号
        String account = LoginContextHolder.getContext().getUser().getName();
        //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        //获取用户id
        Long userId = LoginContextHolder.getContext().getUser().getId();
        //查询该用户电话
        String phone = btyTxlService.getPhone(userId);

        int role = 0;
        List<Long> roleList = user.getRoleList();
        for (Long name:roleList) {
            if(name.longValue()==new Long("1283292980305018882").longValue()){//督导
                role = 1;

                //营运经理
            }else if (name.longValue()==new Long("1308249608428101633").longValue()){
                role = 2;

                //营运经理助理
            } else if (name.longValue()==new Long("1351005338099499010").longValue()){
            role = 3;
            }
        }

        Page<Map<String, Object>> list = null;

        //督导
        if(role==1){
           dd = account;
           tel = phone;
           list = this.btyTxlService.listDd(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);

           //营运经理
        }else if (role == 2){
            yyjl = account;
            tel = phone;
            list = this.btyTxlService.listYy(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);

         //营运经理助理
        } else if (role == 3){
            //查询该营运经理助理对应的营运经理
            BtyTxl btyTxl = this.btyTxlService.getYyjl(account, phone);

            //姓名电话都不为空
            if (btyTxl.getYyjlqy() != null && btyTxl.getYytel() != null){
                //营运经理助理对应营运经理
                yyjl = btyTxl.getYyjlqy();
                tel = btyTxl.getYytel();
                list = this.btyTxlService.listZl(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);
            }
        }else {
            list = this.btyTxlService.list(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, status);
        }

//        Page<Map<String, Object>> list = this.btyTxlService.list(ctbh, dm, csqy, yyjl, dd, beginTime, endTime);
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long id) {
        this.btyTxlService.delete(id);
        return SUCCESS_TIP;
    }


    /**
     * 跳转到修改页面  没用到人员表
     * 没用到人员表的情况下 只修改餐厅表
     *
     * @return
     */
    @RequestMapping(value = "/btyTxl_update/{id}")
    public String btyTxl_update(@PathVariable Long id, Model model) {
        BtyTxl btyTxl = this.btyTxlService.getByID(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyTxl));
        LogObjectHolder.me().set(btyTxl);
        return PREFIX + "btyTxl_editCT.html";
    }

    @RequestMapping(value = "/btyTxlWm_update/{gcgWsjdId}")
    public String btyTxlWm_update(@PathVariable String gcgWsjdId, Model model) {
        TakeAwayResult result=btyTxlService.takeAwayTxl(gcgWsjdId);
        model.addAllAttributes(BeanUtil.beanToMap(result));
        LogObjectHolder.me().set(result);
        return PREFIX + "btyTxlWaiMai_edit.html";
    }

    /**
     * 开始修改
     */
    @ResponseBody
    @RequestMapping(value = "/update")
    public Object update(BtyTxl btyTxl) {
        if (ToolUtil.isOneEmpty(btyTxl, btyTxl.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //修改餐厅编号
        if (ToolUtil.isNotEmpty(btyTxl.getCtbh())) {
            btyTxlService.updateCtbh(btyTxl);
        }

        return btyTxlService.renew(btyTxl);

    }
    @ResponseBody
    @RequestMapping(value = "/WaiMai_update")
    public ResponseData WaiMai_update(TakeAwayResult takeAwayResult) {
        if (ToolUtil.isOneEmpty(takeAwayResult, takeAwayResult.getWsjdId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        GcgWsjd wsjd =wsjdService.getById(takeAwayResult.getWsjdId());
        if(ToolUtil.isNotEmpty(takeAwayResult.getYyjl())){
            wsjd.setYyjl(takeAwayResult.getYyjl());
            wsjdService.updateById(wsjd);
        }
        return ResponseData.success();

    }

    /**
     * 修改状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus")
    public Object updateStatus(BtyTxl btyTxl) {
        if (ToolUtil.isOneEmpty(btyTxl, btyTxl.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

        return btyTxlService.updateStatus(btyTxl);

    }

    /**
     * 获取通讯录导出excel列表(不分页)
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(String ctbh, String dm, String csqy, String yyjl, String dd,String timeLimit, Integer status, HttpServletResponse response) {

        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1] + " 23:59:59";
        }

        //获取用户的帐号
        String account = LoginContextHolder.getContext().getUser().getName();
        //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        int role = 0;
        List<Long> roleList = user.getRoleList();
        for (Long name:roleList) {
            if(name.longValue()==new Long("1283292980305018882").longValue()){//督导
                role = 1;
                //营运经理
            }else if (name.longValue()==new Long("1308249608428101633").longValue()){
                role = 2;
            }
        }
        if(role==1){
            dd = account;

            //营运经理
        }else if (role == 2){
            yyjl = account;
        }
        this.btyTxlService.listExport(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, status, response);
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/btyTxl_addct")
    public String btyTxl_addct() {
        return PREFIX + "btyTxl_addct.html";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/btyTxl_addfzr")
    public String btyTxl_addfzr() {
        return PREFIX + "btyTxl_addfzr.html";
    }

    @RequestMapping(value = "/addfzr")
    @ResponseBody
    public Object addfzr(BtyTxlRY btyTxlRY) {
        return this.btyTxlService.addfzr(btyTxlRY);
//        return SUCCESS_TIP;
    }

    @ResponseBody
    @RequestMapping(value = "/addct")
    public Object addct(BtyTxl btyTxl) {
       return this.btyTxlService.addct(btyTxl);
    }

    @RequestMapping(value = "/btyTxl_view/{id}")
    public String btyTxl_view(@PathVariable Long id) {
        ct_id = id;
        return PREFIX + "btyTxl_view.html";
    }

    @RequestMapping(value = "/view")
    @ResponseBody
    public Object view() {
        Page<Map<String, Object>> list = this.btyTxlService.view(ct_id);
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    @RequestMapping(value = "/view_delete")
    @ResponseBody
    public Object view_delete(@RequestParam Long pid) {
        this.btyTxlService.view_delete(pid);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/view_update_getByID/{pid}")
    public String view_update_getByID(@PathVariable Long pid, Model model) {
        BtyTxlRY btyTxlRY = this.btyTxlService.view_update_getByID(pid);
        model.addAllAttributes(BeanUtil.beanToMap(btyTxlRY));
        LogObjectHolder.me().set(btyTxlRY);
        return PREFIX + "btyTxl_view_edit.html";
    }

    @RequestMapping(value = "/view_update")
    @ResponseBody
    public Object view_update(BtyTxlRY btyTxlRY) {
        if (ToolUtil.isOneEmpty(btyTxlRY, btyTxlRY.getPid())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.btyTxlService.view_update(btyTxlRY);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/selectTerm")
    @ResponseBody
    public Object selectDD(String term){
        List<BtyTxl> list = this.btyTxlService.selectTerm(term);
        System.out.println(list.toString());
        return list;
    }

    /**
     * 查询所有营运经理及其电话
     * @return
     */
    @RequestMapping(value = "/selectYy")
    @ResponseBody
    public Object selectYy(String yyjl){
        List<BtyTxl> list = this.btyTxlService.selectYy(yyjl);
        System.out.println(list.toString());
        return list;
    }

    /**
     * 查询营运经理列表
     *
     * @return
     */
    @RequestMapping(value = "/selectYyjlList")
    @ResponseBody
    public Object selectYyjlList() {
        List<YyjlResult> list = teamService.selectYyjlLists();
        for (YyjlResult yyjlResult : list) {
            if(yyjlResult.getYyjl().equals("汪晓林")){
                yyjlResult.setYyjl("潘忠康");
            }
            else if(yyjlResult.getYyjl().equals("王业付")){
                yyjlResult.setYyjl("屈玉泉");
            }
            else if(yyjlResult.getYyjl().equals("孙课=姚翠芳")){
                yyjlResult.setYyjl("孙课");
            }
        }
        return list;
    }

    /**
     * 修改店长，餐厅电话
     * @return
     */
    @RequestMapping(value = "/editPerson")
    @ResponseBody
    public Object editPerson(BtyTxl btyTxl)
    {
        return this.btyTxlService.editPerson(btyTxl);
    }

    /**
     * 查询店名
     *
     */
    @RequestMapping(value = "/getDm")
    @ResponseBody
    public List<BtyTxl> getDictionaryType(){
        //获取是否是督导
        String rem = LoginContextHolder.getContext().getUser().getAvatar();
        //当前登陆者姓名
        String account = LoginContextHolder.getContext().getUser().getName();
        //账号
        String username = LoginContextHolder.getContext().getUser().getAccount();
        //当前登陆者角色集
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<BtyTxl> list = null;

        if(roleNames.contains("督导")){
            list = btyTxlService.ddList(account);

        }else if (roleNames.contains("营运经理")){
            list = btyTxlService.yyList(account);

            //人事及管理员
        }else {
            list = btyTxlService.list();
        }

        return list;
    }


    /**
     * 查询店名对应餐厅编号
     */
    @RequestMapping(value = "/getBh")
    @ResponseBody
    public Object getBh(String dm) {
        return btyTxlService.getBh(dm);
    }


    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUser(@RequestParam("file") MultipartFile file) {

        String fileName = file.getOriginalFilename();//文件名
        Boolean flag;
        JsonResult jsonResult = new JsonResult();
        try {
            flag = btyTxlService.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return flag;

    }


    /**
     * 导入外卖通讯录excel
     */
    @RequestMapping("/importWm")
    @ResponseBody
    public Object importWm(@RequestParam("file") MultipartFile file) {

        String fileName = file.getOriginalFilename();//文件名
        Boolean flag;
        JsonResult jsonResult = new JsonResult();
        try {
            flag = btyTxlService.importWm(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return flag;

    }


    /**
     * 同步店长信息
     */
    @ResponseBody
    @RequestMapping(value = "/updateDz")
    public ResponseData updateDz() {
        //同步店长信息
        return btyTxlService.updateDz();

    }

    /**
     * 同步营运架构
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateYy")
    public ResponseData updateYy(){
        //同步营运架构
        return btyTxlService.updateYy();
    }

    /**
     * 更新财务码
     */
    @ResponseBody
    @RequestMapping(value = "/updateCwm")
    public ResponseData updateCwm() {
        //更新财务码
        return btyTxlService.updateCwm();

    }

    /**
     * 同步外卖店名
     */
    @ResponseBody
    @RequestMapping(value = "/editWmDm")
    public ResponseData editWmDm() {
        //同步外卖店名
        return btyTxlService.editWmDm();
    }

}
